<template>
  <el-dialog
    title="新增航班"
    :visible.sync="dialogVisible"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="航线名称" prop="carName">
        <el-input 
          v-model="form.carName"
          placeholder="请输入航线名称"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="起始地" prop="cfrom">
        <el-select
          v-model="form.cfrom"
          filterable
          placeholder="请选择起始地"
        >
          <el-option
            v-for="city in cities"
            :key="city.value"
            :label="city.label"
            :value="city.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="目的地" prop="cto">
        <el-select
          v-model="form.cto"
          filterable
          placeholder="请选择目的地"
        >
          <el-option
            v-for="city in cities"
            :key="city.value"
            :label="city.label"
            :value="city.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="起飞时间" prop="start">
        <el-date-picker
          v-model="form.start"
          type="datetime"
          placeholder="选择起飞时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="startTimeOptions"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="到达时间" prop="end">
        <el-date-picker
          v-model="form.end"
          type="datetime"
          placeholder="选择到达时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="endTimeOptions"
        >
        </el-date-picker>
      </el-form-item>
      
      <el-form-item label="航班类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择航班类型">
          <el-option label="经济型" value="经济型"></el-option>
          <el-option label="舒适型" value="舒适型"></el-option>
          <el-option label="豪华型" value="豪华型"></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="车牌号" prop="carNumber">
        <el-input v-model="form.carNumber" placeholder="请输入车牌号"></el-input>
      </el-form-item> -->

      <el-form-item label="价格" prop="price">
        <el-input-number 
          v-model="form.price" 
          :min="0"
          :precision="2"
          :step="10"
        ></el-input-number>
        <span class="unit">元</span>
      </el-form-item>

      <el-form-item label="图片" prop="img">
        <el-upload
          class="car-uploader"
          action="/api/PicServlet"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
          name="file"
        >
          <img v-if="form.img" :src="concatPic(form.img)" class="car-image">
          <i v-else class="el-icon-plus car-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          type="textarea"
          v-model="form.description"
          :rows="3"
          placeholder="请输入航班描述"
        ></el-input>
      </el-form-item>

     
    </el-form>

    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'CarAdd',

  props: {
    visible: {
      type: Boolean,
      default: false
    },
    car: {
      type: Object,
      default: null
    }
  },

  data() {
    const validateCarName = (rule, value, callback) => {
      if (!value || !value.toString().trim()) {
        callback(new Error('请输入航线名称'))
        return
      }
      const trimmedValue = value.toString().trim()
      if (trimmedValue.length < 2) {
        callback(new Error('航线名称不能少于2个字符'))
        return
      }
      if (trimmedValue.length > 50) {
        callback(new Error('航线名称不能超过50个字符'))
        return
      }
      callback()
    }

    const validateEndTime = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择到达时间'))
        return
      }
      if (!this.form.start) {
        callback(new Error('请先选择起飞时间'))
        return
      }
      if (new Date(value) <= new Date(this.form.start)) {
        callback(new Error('到达时间必须晚于起飞时间'))
        return
      }
      callback()
    }

    return {
      dialogVisible: false,
      submitting: false,
      cities: [
        { value: '北京', label: '北京' },
        { value: '上海', label: '上海' },
        { value: '广州', label: '广州' },
        { value: '深圳', label: '深圳' },
        { value: '成都', label: '成都' },
        { value: '杭州', label: '杭州' },
        { value: '武汉', label: '武汉' },
        { value: '西安', label: '西安' },
        { value: '重庆', label: '重庆' },
        { value: '南京', label: '南京' },
        { value: '厦门', label: '厦门' },
        { value: '昆明', label: '昆明' },
      ],
      form: {
        carName: '',
        cfrom: '',
        cto: '',
        type: '',
        price: 0,
        img: '',
        description: '',
        start: '',
        end: ''
      },
      startTimeOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      endTimeOptions: {
        disabledDate(time) {
          if (!this.form.start) return true;
          return time.getTime() < new Date(this.form.start).getTime();
        }
      },
      rules: {
        carName: [
          { required: true, validator: validateCarName, trigger: ['blur', 'change'] }
        ],
        cfrom: [
          { required: true, message: '请选择起始地', trigger: 'change' }
        ],
        cto: [
          { required: true, message: '请选择目的地', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择航班类型', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { type: 'number', min: 0, message: '价格必须大于0', trigger: 'blur' }
        ],
        img: [
          { required: true, message: '请上传航班图片', trigger: 'change' }
        ],
        start: [
          { required: true, message: '请选择起飞时间', trigger: 'change' }
        ],
        end: [
          { required: true, validator: validateEndTime, trigger: 'change' }
        ]
      }
    }
  },

  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val && this.car) {
        const [type, ...descParts] = this.car.cinfo.split(' - ')
        this.form = {
          carName: this.car.cname,
          cfrom: this.car.cfrom,
          cto: this.car.cto,
          type: type,
          price: this.car.crent,
          img: this.car.cimg,
          description: descParts.join(' - ') || '',
          start: this.car.start || '',
          end: this.car.end || ''
        }
      } else {
        this.handleClose()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },

  methods: {
    handleClose() {
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.form = {
        carName: '',
        cfrom: '',
        cto: '',
        type: '',
        price: 0,
        img: '',
        description: '',
        start: '',
        end: ''
      }
    },

    concatPic(path) {
      if (!path) return ''
      if (path.startsWith('http')) return path
      return 'http://localhost:8080/exam_war' + path
    },

    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }

      return isImage && isLt2M
    },

    handleUploadSuccess(res) {
      if (res.code === 0) {
        this.form.img = res.data.url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },

    async handleSubmit() {
      try {
        const valid = await this.$refs.form.validate()
        if (!valid) {
          return
        }
        
        this.submitting = true
        const params = new URLSearchParams()
        if (this.car) {
          params.append('cid', this.car.cid)
        }
        params.append('cname', (this.form.carName || '').trim())
        params.append('cfrom', this.form.cfrom)
        params.append('cto', this.form.cto)
        params.append('cinfo', `${this.form.type} - ${this.form.description}`.trim())
        params.append('cimg', this.form.img)
        params.append('crent', this.form.price)
        params.append('status', this.car ? this.car.status : '1')
        params.append('start', this.form.start)
        params.append('end', this.form.end)
        
        const res = await request.post('/car/save', params)
        
        if (res.code === 0) {
          this.$message.success(this.car ? '更新成功' : '添加成功')
          this.$emit('success')
          this.dialogVisible = false
          this.handleClose()
        } else {
          this.$message.error(res.msg || (this.car ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error(this.car ? '更新航班失败:' : '添加航班失败:', error)
        this.$message.error(error.message || (this.car ? '更新失败' : '添加失败'))
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.car-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    
    &:hover {
      border-color: #409EFF;
    }
  }
}

.car-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.car-image {
  width: 178px;
  height: 178px;
  display: block;
}

.unit {
  margin-left: 10px;
  color: #666;
}

.el-date-picker {
  width: 100%;
}

.el-form-item {
  margin-bottom: 22px;
  
  &.is-error {
    margin-bottom: 18px;
  }
}
</style> 